import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import to from '../../../../utils/to';
const $api = require('../../../../request/api').API;
Page({
  data: {
    selectionDialog: {
      show: false,
      data: [],
      selectedOptions: undefined,
      selectedOptionsIndex: 0
    },
    history: [],
    numberPeople: 1,
    address: '',
    trapDesc: '',
    beeperId: '',
    selectorShow: false,
    selectedOptions: [],
    video: '',
    videoBase64: '',
    residentAddress: {
      fieldNames: {
        text: 'name',
        value: 'id'
      },
      name: '',
      columns: []
    }
  },
  onLoad: function (options) {
    const { beeperId } = options;
    this.setData({ beeperId });
    this.fetchResidentAddressList();
    this.handleObtainInitialData(beeperId);
  },

  /**
   * 获取初始数据
   */
  handleObtainInitialData(beeperId) {
    Toast.loading({ message: '加载中...', forbidClick: true });
    $api
      .checkoutAlarmAndTrapped({ beeperId })
      .then(res => {
        const {
          alarmList,
          unitId,
          unitName,
          buildId,
          buildName,
          floorId,
          floorName,
          houseNumber,
          houseNumberId,
          reportCount,
          type
        } = res.data.data;
        if (type === 1) {
					Dialog.confirm({
						title: '提示',
						confirmButtonText: '新增消防报警',
						cancelButtonText: '取消上报',
						message: `24小时内无火灾报警，无需上报`
					}).then(() => {
						wx.redirectTo({
							url: '/subcontract/home/pages/fireDetection/index?beeperId=' + this.data.beeperId + '&btnId=' + 0
						});
					})
					.catch(() => {
						wx.navigateBack({
							delta: 1
						})
					});
        }

        const selectedOptions = [
          { id: buildId, name: buildName },
          { id: unitId, name: unitName },
          { id: floorId, name: floorName },
          { id: houseNumberId, name: houseNumber }
        ];

        if (alarmList.length === 1) {
          this.setData({
            'selectionDialog.data': alarmList,
            'selectionDialog.selectedOptions': alarmList[0]
          });
          this.fetchListDataAlarmFire(alarmList[0].alarmId);
        }

        if (alarmList.length > 1) {
          this.setData({
            'selectionDialog.show': true,
            'selectionDialog.data': alarmList,
            'selectionDialog.selectedOptions': alarmList[0]
          });
        }

        if (alarmList.length === 0) {
        	Dialog.confirm({
						title: '提示',
						confirmButtonText: '新增消防报警',
						cancelButtonText: '取消上报',
						message: `24小时内无火灾报警，无需上报`
					}).then(() => {
							wx.redirectTo({
								url: '/subcontract/home/pages/fireDetection/index?beeperId=' + this.data.beeperId + '&btnId=' + 0
							});
					})
					.catch(() => {
						wx.navigateBack({
							delta: 1
						})
					});
        }

        this.setData({
          selectedOptions,
          'residentAddress.name': `${buildName ? buildName + '/' : ''}${unitName ? unitName + '/' : ''}${floorName ? floorName + '/' : ''}${houseNumber ? houseNumber + '/' : ''}`
        });
        Toast.clear();
      })
      .catch(() => {
        Toast.clear();
      });
  },

  /**
   * 报警集合选择确认
   */
  handleDialogConfirm() {
    const { selectionDialog } = this.data;
    this.fetchListDataAlarmFire(selectionDialog.selectedOptions.alarmId);
  },

  /**
   * 根据报警id查询火情上报历史集合
   * @param alarmId
   */
  fetchListDataAlarmFire(alarmId) {
    Toast.loading({ message: '加载中...', forbidClick: true });
    $api
      .ListDataAlarmTire({ alarmId })
      .then(res => {
        const history = res.data.data.map(c => {
          return {
            ...c,
            address: c.site + c.buildName + c.unitName + c.floorName + c.houseNumber
          };
        });
        this.setData({ history });
        Toast.clear();
      })
      .catch(() => {
        Toast.clear();
      });
  },

  /**
   * 发送上报
   */
  handleSendReport() {
    const {
      selectedOptions,
      residentAddress,
      address,
      numberPeople,
      videoBase64,
      selectionDialog,
      latitude,
      longitude,
      trapDesc
    } = this.data;
    if (!residentAddress.name && !address) {
      Toast.fail('所在楼层或详细位置必须填写一个');
      return false;
    }
    const params = {
      alarmId: selectionDialog.selectedOptions.alarmId,
      trapNum: numberPeople,
      trapVideos: videoBase64,
      site: address,
      trapDesc
    };
    if (selectedOptions.length >= 1 && selectedOptions[0].id) {
      params.buildId = selectedOptions[0].id;
      params.buildName = selectedOptions[0].name;
    }
    if (selectedOptions.length >= 2 && selectedOptions[1].id) {
      params.unitId = selectedOptions[1].id;
      params.unitName = selectedOptions[1].name;
    }
    if (selectedOptions.length >= 3 && selectedOptions[2].id) {
      params.floorId = selectedOptions[2].id;
      params.floorName = selectedOptions[2].name;
    }
    if (selectedOptions.length >= 4 && selectedOptions[3].id) {
      params.houseNumberId = selectedOptions[3].id;
      params.houseNumber = selectedOptions[3].name;
    }

    if (latitude && longitude) {
      params.latitude = latitude.toString();
      params.longitude = longitude.toString();
    }
    Toast.loading({ message: '上报中...', forbidClick: true });
    $api
      .sendReportAlarmTrap(params)
      .then(res => {
        Toast.success('上报成功');
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 800);
      })
      .catch(err => {
        Toast.fail(err.msg || '上报失败');
      });
  },

  /**
   * 选中弹出层中的报警项目
   */
  handleSelectDialogOption(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      'selectionDialog.selectedOptionsIndex': index,
      'selectionDialog.selectedOptions': this.data.selectionDialog.data[index]
    });
  },

  /**
   * 选择视频
   */
  handleSelectAddVideo() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: res => {
        let tempFilePath = res.tempFiles[0].tempFilePath;
        const videoBase64 = wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, 'base64');
        this.setData({ video: tempFilePath, videoBase64 });
      }
    });
  },

  /**
   * 获取该小区下的楼顶至门牌号
   */
  fetchResidentAddressList() {
    const { beeperId } = this.data;
    $api.getResidentAddressList({ beeperId }).then(res => {
      this.setData({
        'residentAddress.columns': res.data.data
      });
    });
  },

  /**
   * 楼栋选择器选择
   */
  handleResidentAddressChange(e) {
    const { selectedOptions } = e.detail;
    const fieldValue = selectedOptions.map(option => option.text || option.name).join('/');

    this.setData({
      'residentAddress.name': fieldValue,
      selectedOptions: e.detail.selectedOptions.map(c => {
        return { id: c.id, name: c.name };
      })
    });
  },

  /**
   * 清空楼栋层选择数据
   */
  handleWipeOptionData() {
    this.setData({ 'residentAddress.name': '', selectedOptions: [] });
  },

  /**
   * 打开楼栋层选择器
   */
  showResidentAddressPopup() {
    this.setData({ selectorShow: true });
  },

  /**
   * 关闭楼栋层选择器
   */
  closeResidentAddress() {
    this.setData({ selectorShow: false });
  },

  /**
   * 输入框输入
   * @param e
   */
  handleTextareaInput(e) {
    const { remark } = e.target.dataset;
    if (remark === 'address') this.setData({ address: e.detail.value });
    if (remark === 'numberPeople') this.setData({ numberPeople: e.detail });
    if (remark === 'trapDesc') this.setData({ trapDesc: e.detail.value });
  },

  /**
   * 清除视频
   */
  handleClearVideo() {
    this.setData({ video: '' });
  },

  /**
   * 选择位置
   */
  handleSelectAddress() {
    Dialog.confirm({
      title: '提示',
      confirmButtonText: '清除所选楼栋层',
      cancelButtonText: '不清除',
      message: `选择地址需要清除已选择的楼栋层吗？`
    })
      .then(() => {
        this.handleWipeOptionData();
        this.getLatitudeLongitudeAddress();
      })
      .catch(() => {
        this.getLatitudeLongitudeAddress();
      });
  },
  async getLatitudeLongitudeAddress() {
    Toast({ type: 'loading', message: '获取定位中', duration: 0 });
    const [err, location] = await to(wx.getLocation());
    if (err) {
      Toast.clear();
      Toast.fail('请打开小程序定位授权');
      Dialog.alert({ title: '提示', message: `打开小程序授权设置` }).then(() => {
        wx.openSetting();
      });
      return;
    }
    Toast.clear();
    wx.chooseLocation({
      latitude: location.latitude,
      longitude: location.longitude,
      success: res => {
        Toast.success('获取详细位置成功');
        this.setData({ address: res.address, longitude: res.longitude, latitude: res.latitude });
      },
      fail: err => {
        console.log(err);
      }
    });
  }
});
